package br.leiam.eolica.graficos;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.text.NumberFormat;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;

import org.jfree.chart.ChartUtilities;

import sun.misc.BASE64Encoder;

public class Tabela extends JPanel {
    
	public static final String[] columnNames = {
        "Velocidade(m/s)", "Frequencia(%)", "Pot. Aerog.(kW)", "f(v).p(v)"
    };
	

    protected JTable table;
    protected JScrollPane scroller;
    protected MyTableModel tableModel;
	private  Dados dados;   
	private JLabel jLabel2, jLabel3;


	private final int imageHeight;
	private final int imageWidth;
   

    public Tabela(Dados dados,int imageHeight, int imageWidth) {
        this.dados = dados;
		this.imageHeight = imageHeight;
		this.imageWidth = imageWidth;
		
		initComponent();
        table.setSurrendersFocusOnKeystroke(true);
        //this.setSize(imageWidth, imageHeight);
        //this.setPreferredSize(new Dimension(imageWidth, imageHeight));         
        
    }

    public void initComponent() {
        tableModel = new MyTableModel(columnNames,dados);
        //tableModel.addTableModelListener(new InteractiveForm.InteractiveTableModelListener());
        table = new JTable();
        table.setModel(tableModel);
        table.setSurrendersFocusOnKeystroke(true);
       
        scroller = new javax.swing.JScrollPane(table);
        table.setPreferredScrollableViewportSize(new java.awt.Dimension(imageWidth, imageHeight));
        
        setLayout(new BorderLayout());
        JPanel painelInferior = construirLabelsePainel();
        painelInferior.setBackground(Color.WHITE);
		add(painelInferior, BorderLayout.SOUTH);
        
		setRodape((dados.getSumfvpv()));
		setLabelEAG(dados.getEag());
		setBackground(Color.WHITE);
        
    }
    
    public void setRodape(double valor) {

		NumberFormat formatador = NumberFormat.getInstance();
		formatador.setMaximumFractionDigits(2);
		jLabel2.setText("TOTAL f(v).P(v) " + formatador.format(valor));
	}

	public void setLabelEAG(double valor) {
		NumberFormat formatador = NumberFormat.getInstance();
		formatador.setMaximumFractionDigits(2);
		jLabel3.setText("EAG = sum(f(v).P(v))*8760 = "
				+ formatador.format(valor) + " GWh");

	}

	private JPanel construirLabelsePainel() {
		JLabel jLabel = new JLabel("Teste");
		jLabel.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
		jLabel.setText("Tabela. Passos para determinacao da energia anual gerada EAG");
		add(jLabel, BorderLayout.NORTH);
        add(scroller, BorderLayout.CENTER);
        jLabel2 = new JLabel("jLabel2");
        jLabel3 = new JLabel("jLabel3");
        
        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14));
		jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
		jLabel2.setText("jLabel2");

		jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14));
		jLabel3.setText("jLabel3");
        
        
        JPanel painelInferior = new JPanel();
        painelInferior.setLayout(new BorderLayout());
        painelInferior.add(jLabel2, BorderLayout.NORTH);
        painelInferior.add(jLabel3, BorderLayout.SOUTH);
		return painelInferior;
	}

    public void highlightLastRow(int row) {
        int lastrow = tableModel.getRowCount();
        if (row == lastrow - 1) {
            table.setRowSelectionInterval(lastrow - 1, lastrow - 1);
        } else {
            table.setRowSelectionInterval(row + 1, row + 1);
        }

        table.setColumnSelectionInterval(0, 0);
    }

  
    
    public void tableChanged(TableModelEvent evt) {
        if (evt.getType() == TableModelEvent.UPDATE) {
            int column = evt.getColumn();
            int row = evt.getFirstRow();
            System.out.println("row: " + row + " column: " + column);
            table.setColumnSelectionInterval(column + 1, column + 1);
            table.setRowSelectionInterval(row, row);
        }
    }
    
    public String getBase64String() {
		String figura = "";
		this.setVisible(true);
		repaint();
		try {
			double escalaX = 1, escalaY = 1;
			Component co = this;
			BufferedImage bi = new BufferedImage(
					(int) (co.getSize().getWidth() * escalaX), (int) (co
							.getSize().getHeight() * escalaY),
					BufferedImage.TYPE_INT_RGB);
			Graphics2D g2d = bi.createGraphics();
			g2d.scale(escalaX, escalaY);
			co.paint(g2d);

			byte[] figBytes;

			figBytes = ChartUtilities.encodeAsPNG(bi);

			BASE64Encoder encoder = new BASE64Encoder();
			figura = encoder.encode(figBytes);
		} catch (Exception ex) {
			Logger.getLogger(Weibull.class.getName()).log(Level.SEVERE, null,
					ex);
		}
		return figura;
	}
    

  
    
  

    public class InteractiveTableModelListener implements TableModelListener {
        public void tableChanged(TableModelEvent evt) {
            if (evt.getType() == TableModelEvent.UPDATE) {
                int column = evt.getColumn();
                int row = evt.getFirstRow();
                System.out.println("row: " + row + " column: " + column);
                table.setColumnSelectionInterval(column + 1, column + 1);
                table.setRowSelectionInterval(row, row);
            }
        }
    }
}